package com.cvte.sunkit

import android.app.Application
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.media.projection.MediaProjection
import android.util.Log
import com.kongzue.dialogx.DialogX
import com.kongzue.dialogx.style.MaterialStyle
import kotlin.properties.Delegates


@Suppress("DEPRECATION")
class App : Application() {
    private val mPackageList: MutableList<ApplicationInfo> = ArrayList()


    companion object {
        lateinit var mInstance: App
        private const val TAG = "Application"
        var canReadAndWriteFile by Delegates.notNull<Boolean>()
        var mediaProjection: MediaProjection? = null
    }

    override fun onCreate() {
        super.onCreate()
        mInstance = this

        DialogX.init(this) // 初始化弹窗框架
        DialogX.globalStyle = MaterialStyle.style()

    }

    /**
     * 获取应用列表
     * @return
     */
    fun loadAppList(): List<ApplicationInfo> {
        synchronized(App::class.java) {
            if (mPackageList.isEmpty()) {
                loadApplicationList()
            }
        }
        return mPackageList
    }

    /**
     * 加载应用列表
     */
    private fun loadApplicationList() {
        val listPack: MutableList<ApplicationInfo> =
            packageManager.getInstalledApplications(PackageManager.GET_META_DATA) // 加载应用列表

        val removedItems: MutableList<ApplicationInfo> = ArrayList()
        val selfPackage = packageName
        for (pack in listPack) { // 寻找需要移除的应用程序列表
            if (pack.flags and ApplicationInfo.FLAG_SYSTEM > 0) { // 移除系统应用
                removedItems.add(pack)
            }
            if (selfPackage == pack.packageName) { // 移除自身
                removedItems.add(pack)
            }
        }
        listPack.removeAll(removedItems)

        mPackageList.clear()
        mPackageList.addAll(listPack)
        Log.i(TAG, "加载包名列表大小: ${mPackageList.size}  $mPackageList")
    }

}